import React, { PureComponent } from 'react';
import { Select } from 'antd';
import { authTypes } from './ClientUtil';

const { Option } = Select;

class GrantTypeInput extends PureComponent {
  state = {
    value: [],
  };

  componentWillMount() {
    const { props } = this;
    if (props.value) {
      const value = props.value ? props.value.split(',') : [];
      this.setState({ value });
    }
  }

  componentWillReceiveProps(nextProps) {
    const { props } = this;
    if (props.value !== nextProps.value && !nextProps.value) {
      this.setState({ value: [] });
    } else {
      const value = nextProps.value ? nextProps.value.split(',') : [];
      this.setState({ value });
    }
  }

  handleSelectChange = value => {
    const { onChange } = this.props;
    this.setState({ value });
    if (onChange) onChange(value.join(','));
  };

  render() {
    const { value } = this.state;
    return (
      <Select
        style={{ width: '100%' }}
        mode="multiple"
        value={value}
        onChange={this.handleSelectChange}
      >
        {authTypes.map((type, index) => (
          <Option key={index} value={type.value}>
            {type.name}
          </Option>
        ))}
      </Select>
    );
  }
}

export default GrantTypeInput;
